#coding:utf-8
# Create your views here.
from django.views.decorators.cache import cache_page
from django.conf.urls import patterns , url , include
from  django.shortcuts  import  render_to_response
from django.shortcuts import render 

from django.views.decorators.csrf import csrf_exempt, csrf_protect

from django.contrib.auth.decorators import login_required
from jobs.forms import UsersForm
from jobs import forms 
from datetime import datetime  
from django.http import HttpResponse
from django.contrib.auth.models import User


'''
项目列表页
'''
from models import Task,Project,Category,UserProject,TaskCommit,AddLog

#项目列表
#@cache_page(86400)
@login_required
def ProjectList (request , template_file):
    
    project_list = Project.objects.all()
    return render(request , template_file, locals() )
    
#添加项目
@login_required
def ProjectAddView(request,template_file):
    project_form = forms.ProjectAddForm()
    
    return render(request,template_file, locals() )
    

##任务列表
#@cache_page(60*60)
@login_required
def TaskList(request , proj_id  , template_file=""):
    proj_id=long(proj_id)
    project_list = Project.objects.all()#(user = request.user) 

    category_list = Category.objects.filter(proj__id=proj_id)
    return render(request,template_file, locals() )


#显示动态分类数据
@login_required
def TaskShowByCateId(request, proj_id,cate_id,template_file=""):
    task_list = Task.objects.filter(proj__id=proj_id  , cate__id= cate_id,state__lt=4).order_by("-level","-edit")
    #over_task_list = Task.objects.filter(proj__id=proj_id  , cate__id= cate_id,state=4).order_by("-level","-edit")
    over_task_count = Task.objects.filter(proj__id=proj_id  , cate__id= cate_id,state=4).count()    
    return render(request,template_file,locals() )
@cache_page(100)
@login_required
def TaskShowByCateIdWithOver(request, proj_id,cate_id,template_file=""):
    task_list = Task.objects.filter(proj__id=proj_id  , cate__id= cate_id,state=4).order_by("-level","-edit")
    return render(request,template_file,locals() )
        
    
#固定分类数据
@login_required
def TaskShowByConstCate(request, proj_id,cate , template_file=""):
    if cate == "all":
        #over_task_list = Task.objects.filter(proj__id=proj_id , state=4).order_by("-level","-edit")
        over_task_count = Task.objects.filter(proj__id=proj_id , state=4).count()
        task_list = Task.objects.filter(proj__id=proj_id , state__lt=4).order_by("-level","-edit")
    if cate =="me":
        task_list = Task.objects.filter(proj__id=proj_id  , user__id= request.user.id, state__lt=4 ).order_by("-level","-edit")
        #over_task_list = Task.objects.filter(proj__id=proj_id  , user__id= request.user.id, state=4 ).order_by("-level","-edit")
        over_task_count = Task.objects.filter(proj__id=proj_id  , user__id= request.user.id, state=4 ).count()        
    if cate =="bug":
        task_list = Task.objects.filter(proj__id=proj_id  , is_bug= 1,state__lt=4).order_by("-level","-edit")
        #over_task_list = Task.objects.filter(proj__id=proj_id  , is_bug= 1,state=4).order_by("-level","-edit")
        over_task_list = Task.objects.filter(proj__id=proj_id  , is_bug= 1,state=4).count()    
    if cate =="time":
        task_list = Task.objects.filter(proj__id=proj_id  , state__lt=4).order_by("-start_date","-edit")
        order_by_start_date = True
    if cate =="over":
        prv = None
        task_list = Task.objects.filter(proj__id=proj_id  , state= 4).order_by("-level","-edit")
    
    return render(request,template_file,locals() )


#固定分类数据
#@cache_page(100)
@login_required
def TaskShowByConstCateWithOver(request, proj_id,cate , template_file=""):
    if cate == "all":
        task_list = Task.objects.filter(proj__id=proj_id , state=4).order_by("-level","-edit")
    if cate =="me":
        task_list = Task.objects.filter(proj__id=proj_id  , user__id= request.user.id, state=4 ).order_by("-level","-edit")
    if cate =="bug":
        task_list = Task.objects.filter(proj__id=proj_id  , is_bug= 1,state=4).order_by("-level","-edit")
    
    return render(request,template_file,locals() )



#添加任务
@login_required
def TaskAdd(request ,template_file):

    return render(request,template_file , {"task_list":{}})
    
#添加基于cate添加信息。



@login_required
def TaskAddByCate(request, proj_id,cate_id , template_file=""):
    cate = Category.objects.get(id=cate_id)
    c = Task.objects.filter(name=request.POST.get("name") , user__id=request.user.id , cate__id=cate_id).count()
    if c >0 :
        return HttpResponse("erro")
    task = Task(
        name=request.POST.get("name"),
        user=request.user,
        edit=datetime.now(),
        proj=cate.proj,
        cate=cate,
        is_bug=0,
        state=1,
        level=1,
    )
    
    task.save()
    AddLog(task,1)
        
    return render(request,template_file,locals() )


@login_required
def TaskQuickOver(request):
    task = Task.objects.get(id=request.POST.get("id"))
    if task != None and task.user.id == request.user.id:
        
        if request.POST.get("type")  == "2" :
            state = 4
            task.schedule =100
        else:
            if task.state ==1 :
                state = 2
                task.start_date = datetime.now() if task.start_date == None else task.start_date
            
            elif task.state == 2:
                state = 4
                task.schedule= 100
            
        task.state = state
        task.end_date= datetime.now()
        task.save()
        AddLog(task,2)
        
        over = "success"
    else:
        over = "任务不存在，或者不属于你。"
    return HttpResponse(over)

@login_required
@csrf_protect
def TaskInfoEdit(request ,task_id, template_file):
    task = Task.objects.get(id=task_id)
    #"id","name","doc","state","level" , "start_date" , "end_date" , "user"
    info= {
        "id":task.id,
        "name":task.name,
        "cate":task.cate.id,
        "doc":task.doc,
        "level":task.level,
        "state":task.state,
        "start_date":task.start_date,
        "time_long":task.time_long,
        "schedule":task.schedule,
        "user":task.user,
        "is_bug":task.is_bug,
    }
    form= forms.TaskForm(info)
    if request.method=="POST":
        form= forms.TaskForm(request.POST)
        if form.is_valid():
            start_date = request.POST.get("start_date",None).strip()
            if start_date == "":
                start_date = None
            
            cate_id = request.POST.get("cate",task.cate.id)
            cate = Category.objects.get(id=cate_id)
            print(task.state , task.schedule ) 
            task.name=request.POST.get("name",task.name)
            task.cate=cate
            task.level = request.POST.get("level",task.level)
            task.doc = request.POST.get("doc",task.doc)
            task.start_date = start_date
            task.time_long = request.POST.get("time_long" , task.time_long)
            if str(task.state) == "4" and request.POST.get("state") != "4" and str(task.schedule) == request.POST.get("schedule") and task.schedule==100:
                task.state = request.POST.get("state")
            elif str(task.schedule) == "100" and request.POST.get("schedule")!="100" and str(task.state) == request.POST.get("state") and str(task.state) == "4" :
                task.state = 2
                task.schedule = request.POST.get("schedule")
            elif task.schedule != None and task.schedule!=1  and task.state==1 and request.POST.get("state") == "1"  and task.schedule != request.POST.get("schedule"):
                print(task.schedule , task.state)
                task.state=2
                task.schedule = request.POST.get("schedule")
            else:
                task.state = request.POST.get("state",task.state)
                task.schedule = 100 if str(task.state) == "4" else request.POST.get("schedule") ##当状态是 4时， 完成比例默认为100
                task.state =4 if str(task.schedule) == "100" else request.POST.get("state")    #当比例到100时，默认标记结束
             
            task.is_bug = request.POST.get("is_bug",task.is_bug)
            if request.POST.get("user",None) == None:
                u=None
            else:
                u = User.objects.get(id=request.POST.get("user"))
            task.user = u
            task.save()
            AddLog(task,2)
            return HttpResponse("修改成功！")
        else:
            ret ="修改失败：%s" % form.errors
            return HttpResponse(ret)
    commit_list  =TaskCommit.objects.filter(task__id=task_id).order_by("-edit_time")
    return render(request,template_file,locals() )
    
    

urlpatterns=patterns("" , 
   
    (r'^add$' , TaskAdd , {"template_file":"task_add.html"}),
    
    (r"^proj_add$" , ProjectAddView , {"template_file":"project_add.html"}),
    (r'^(?P<proj_id>\d+)/$' , TaskList , {"template_file":"task.html"}),
    url (r'^(?P<proj_id>\d+)/cate_(?P<cate_id>\d+)/over$' , TaskShowByCateIdWithOver , {"template_file":"task_simple_list.html"} , name="overTaskWithCate"),
    (r'^(?P<proj_id>\d+)/cate_(?P<cate_id>\d+)$' , TaskShowByCateId , {"template_file":"task_by_cate.html"}),
    url(r'^(?P<proj_id>\d+)/const_cate_(?P<cate>.+)/over$' , TaskShowByConstCateWithOver, {"template_file":"task_simple_list.html"} , name="overTaskWithConstCate"),
    (r'^(?P<proj_id>\d+)/const_cate_(?P<cate>.+)$' , TaskShowByConstCate , {"template_file":"task_by_cate.html"}),
    (r'^(?P<proj_id>\d+)/task_add_by_cate_(?P<cate_id>\d+)$' , TaskAddByCate , {"template_file":"task_to_dd.html"}),
    (r"^task_quick_over" , TaskQuickOver),
    (r"^dd_task_id_(?P<task_id>\d+)$" , TaskInfoEdit , {"template_file":"task_info.html"}),
    (r'^$' , ProjectList , {"template_file":"project_list.html"}),
     
)
